/*
 * $Id: WholeNumberField.java,v 1.1 2003/05/17 15:33:30 znamenacek Exp $
 *
 * Copyright (c) Tomas Znamenacek
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

package net.sf.vofce.gui;

import javax.swing.JTextField; 
import javax.swing.text.Document; 
import javax.swing.text.PlainDocument; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException;

import java.awt.Toolkit;
import java.text.NumberFormat;
import java.text.ParseException;

/**
 * <code>JTextField</code> extension that only accepts whole numbers.
 *
 * @author Tomas Znamenacek
 */
public class WholeNumberField extends JTextField {
    
	private Toolkit toolkit;
	private NumberFormat integerFormatter;

	public WholeNumberField(int value, int columns) {
		
		super(columns);
		toolkit = Toolkit.getDefaultToolkit();
		integerFormatter = NumberFormat.getNumberInstance();
		integerFormatter.setParseIntegerOnly(true);
		setValue(value);
	}

	public WholeNumberField() {

		super();
		toolkit = Toolkit.getDefaultToolkit();
		integerFormatter = NumberFormat.getNumberInstance();
		integerFormatter.setParseIntegerOnly(true);
	}

	public int getValue() {
		
		int retVal = 0;
		
		try {
			retVal = integerFormatter.parse(getText()).intValue();
		} catch (ParseException e) {
			toolkit.beep();
		}

		return retVal;
	}

	public void setValue(int value) {
		setText(integerFormatter.format(value));
	}

	protected Document createDefaultModel() {
		return new WholeNumberDocument();
	}

	protected class WholeNumberDocument extends PlainDocument {
	
		public void insertString(int offs, String str, AttributeSet a) throws BadLocationException {
			
			char[] source = str.toCharArray();
			char[] result = new char[source.length];
			int j = 0;

			for (int i = 0; i < result.length; i++) {
				if (Character.isDigit(source[i])) {
					result[j++] = source[i];
				} else {
					toolkit.beep();
				}
			}
			
			super.insertString(offs, new String(result, 0, j), a);
		}
	}
}
